package com.sdx.console.promote.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.console.promote.entity.TemplateShare;
import com.sdx.console.promote.service.TemplateShareService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.BeetlSQLException;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 分享模板 接口
 */
@RequestMapping("/promote/templateShare")
@Controller
public class TemplateShareController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(TemplateShareController.class);
    private static final String MODEL = "/promote/templateShare";


    @Resource
	private TemplateShareService templateShareService;
    
    @Resource
    private ResCloudFileService resCloudFileService;
    /* 页面 */

    @GetMapping("/index.do")
    @Function("promote.templateShare.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
	    BeetlSQLException s;
        return view;
    }

    @GetMapping("/edit.do")
    @Function("promote.templateShare.edit")
    @ResponseBody
    public ModelAndView edit(Integer templateId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        TemplateShare templateShare = templateShareService.queryById(templateId);
        view.addObject("templateShare", templateShare);
		try {
			view.addObject("templateShareJson", JacksonUtils.toJsonString(templateShare,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("promote.templateShare.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("promote.templateShare.query")
    @ResponseBody
    public JsonResult<PageQuery> list(TemplateShare condtion)
    {
        PageQuery page = condtion.getPageQuery();
        templateShareService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,TemplateShare templateShare,HttpServletRequest request
							,MultipartFile imgUrlFile,MultipartFile posterFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/share/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(imgUrlFile)) {
			try
			{
		        String imgUrlFileNamePair = FileUtils.upload(subPath,imgUrlFile);
		        String imgUrlStoreFile = imgUrlFileNamePair.split("::")[0];
		        imgUrlStoreFile = subPath+imgUrlStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+imgUrlStoreFile,bucketName,imgUrlStoreFile.substring(1));
				String imgUrlUrl = "https://sdxcomm."+ ConfigService.ossDomain+imgUrlStoreFile;
				templateShare.setImgUrl(imgUrlUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,imgUrlStoreFile,imgUrlUrl,"a","分享模板封面");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
	    if (!FileUtils.isEmptyFile(posterFile)) {
		    try
		    {
			    String posterFileNamePair = FileUtils.upload(subPath,posterFile);
			    String posterStoreFile = posterFileNamePair.split("::")[0];
			    posterStoreFile = subPath+posterStoreFile;
			    AliOSSApi.uploadLocalFile(FileUtils.getRoot()+posterStoreFile,bucketName,posterStoreFile.substring(1));
			    String posterUrl = "https://sdxcomm."+ ConfigService.ossDomain+posterStoreFile;
			    templateShare.setPoster(posterUrl);
			    resCloudFileService.insertResFile(ResCloudFile.ALI,posterStoreFile,posterUrl,"a","分享模板海报");
		    }catch(Exception e) {
			    e.printStackTrace();
			    result.setCode(JsonReturnCode.IO_ERROR.getCode());
			    result.setMsg(e.getMessage());
		    }
	    }
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			templateShare.setCreatedBy(user.getId().intValue());
			templateShare.setCreatedName(user.getName());
			templateShare.setCreatedTime(new Date());
		    templateShare.setUpdatedBy(user.getId().intValue());
		    templateShare.setUpdatedName(user.getName());
		    templateShare.setUpdatedTime(new Date());
			templateShareService.save(templateShare);
		} else {
			templateShare.setUpdatedBy(user.getId().intValue());
			templateShare.setUpdatedName(user.getName());
			templateShare.setUpdatedTime(new Date());
			templateShareService.updateTemplate(templateShare);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("promote.templateShare.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)TemplateShare templateShare,HttpServletRequest request
							,@RequestParam("imgUrlFile") MultipartFile imgUrlFile,@RequestParam("posterFile") MultipartFile posterFile
		)
    {

        return save(true,templateShare,request
					,imgUrlFile,posterFile
		);
    }

    @PostMapping("/update.json")
    @Function("promote.templateShare.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  TemplateShare templateShare,HttpServletRequest request
							,@RequestParam("imgUrlFile") MultipartFile imgUrlFile,@RequestParam("posterFile") MultipartFile posterFile
		) {
		return save(false,templateShare,request
		,imgUrlFile,posterFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("promote.templateShare.query")
    @ResponseBody
    public JsonResult<TemplateShare>queryInfo(Integer templateId) {
        TemplateShare templateShare = templateShareService.queryById( templateId);
        return  JsonResult.success(templateShare);
    }

    @PostMapping("/delete.json")
    @Function("promote.templateShare..del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        templateShareService.batchDelTemplateShare(idList);
        return JsonResult.success();
    }
    

}
